//
//  NotificationCellViewModel.m
//  CommentPage
//
//  Created by 欧杨 on 2020/12/3.
//

#import "NotificationCellViewModel.h"
#import <AFNetworking.h>

@implementation NotificationCellViewModel

- (instancetype)initWithNotificationModel:(NotificationModel *)notification
{
    self = [super init];
    if (self) {
        self.notificationModel = notification;
        //self.avater = [UIImage imageNamed:_notificationModel.user.Avatar]; //根据URL字符串获取头像
        self.avater = [UIImage imageNamed:@"an.jpg"];
        self.content = _notificationModel.data.Content;
        self.date = [NSDate dateWithTimeIntervalSince1970:_notificationModel.data.CreateTime/1000];
        self.isRead = _notificationModel.data.Read;
        self.type = _notificationModel.data.Type;
        self.userName = _notificationModel.user.Name;
    }
    return self;
}

- (void)read
{
    if (!self.isRead) {
        NSString *notificationID = self.notificationModel.data.ID;
        NSString *URLString = [NSString stringWithFormat:@"%@%@", @"http://172.18.178.56/api/notification/read/", notificationID];
        NSDictionary *postParam = @{@"isRead":@YES};
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        [manager PATCH:URLString parameters:postParam success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"已读 %@",responseObject);
            if ([responseObject[@"State"]  isEqual: @"success"]) {
                self.isRead = YES;
                self.notificationModel.data.Read = YES;
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"failed");
        }];
    }
}

@end
